// @flow

const st = typeof localStorage === 'object' ? localStorage : {};

type Storage = {
    set(key: string, value: any): void,
    get(key: string): ?any,
    remove(key: string): void
};

export const keys = {
    blog: '__melog_blog__',
    auth: '__melog_auth__',
    name: '__melog_name__'
};

const storage: Storage = {
    setStr(key, value) {
        st[key] = value;
    },
    set(key, value) {
        st[key] = JSON.stringify(value);
    },
    getStr(key) {
        if (!st[key]) return null;
        const value = st[key];
        try {
            const parsed = value;
            return parsed;
        } catch (e) {
            return value;
        }
    },
    get(key) {
        if (!st[key]) return null;
        const value = st[key];
        try {
            const parsed = JSON.parse(value);
            return parsed;
        } catch (e) {
            return value;
        }
    },
    remove(key) {
        delete st[key];
    }
};

export default storage;
